package com.nakanomay.zkcase2;

import org.apache.zookeeper.KeeperException;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * Created with IntelliJ IDEA.
 *
 * @author nakano_may丶
 * @date 2023/4/18
 * @Version 1.0
 * @description 分布式锁测试
 */
public class DistributedLockTest
{
    public static void main(String[] args) throws IOException, InterruptedException, KeeperException
    {
        final DistributedLock lock1 = new DistributedLock();
        final DistributedLock lock2 = new DistributedLock();

        new Thread(()->{
            try {
                lock1.zkLock();
                System.out.println("线程1 启动，获取到锁");

                TimeUnit.SECONDS.sleep(5);
                lock1.unZkLock();
                System.out.println("线程1 释放锁");
            }
            catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        new Thread(()->{
            try {
                lock2.zkLock();
                System.out.println("线程2 启动，获取到锁");

                TimeUnit.SECONDS.sleep(5);
                lock2.unZkLock();
                System.out.println("线程2 释放锁");
            }
            catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }
}
